package br.com.roteador.component;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Observable;

import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import br.com.roteador.localizacao.Localizacao;

@Named("localizacaoNotification")
@Singleton
public class LocalizacaoNotification extends Observable implements Runnable {
	private Boolean hasNewLocation = false;
	private HttpServletRequest req;
	private HttpServletResponse res;
	private PrintWriter writer;
	private Localizacao local;
	
	@Inject
	public LocalizacaoNotification(){}

	//@Observes 
	public void observaLocalizacao(Localizacao localizacao){
		local = localizacao;
		hasNewLocation = true;
		setChanged();
	}
	
	@Override
	public void run() {
	    // SSE data field
	    // last field with blank new line
		while(true){
			if(hasChanged()){
				if(hasNewLocation){
			        writer.write("data: " + local.getImei() + " \n\n");
			        writer.flush();
			        hasNewLocation = false;
				}
			}
		    try {
		    	Thread.sleep(3000);
		    } catch(InterruptedException iex) {
		        iex.printStackTrace();
		    }
		}
	}

	public HttpServletRequest getReq() {
		return req;
	}

	public void setReq(HttpServletRequest req) {
		this.req = req;
	}

	public HttpServletResponse getRes() {
		return res;
	}

	public void setRes(HttpServletResponse res) {
		this.res = res;
		try {
			writer = res.getWriter();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public Boolean getHasNewLocation() {
		return hasNewLocation;
	}

	public void setHasNewLocation(Boolean hasNewLocation) {
		this.hasNewLocation = hasNewLocation;
	}
	
}